package cn.tedu.antcolony.passport.security;

import cn.tedu.antcolony.passport.mapper.AdminMapper;
import cn.tedu.antcolony.passport.pojo.vo.AdminLoginInfoVo;
import cn.tedu.antcolony.passport.service.IPermissionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Component
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private AdminMapper adminMapper;

    @Resource
    private IPermissionService iPermissionService;


    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        log.debug("用户名：{}", s);
        AdminLoginInfoVo loginInfoByUsername = adminMapper.getLoginInfoByUsername(s);
        //从数据库中查询用户是否重复
        if (loginInfoByUsername==null) {
            log.debug("登录失败,该用户不存在!");
            return null;
        }

        //根据id获取用户所拥有的权限 List<SimpleGrantedAuthority>
        List<String> permissions = iPermissionService.getPermissionsByUserId(loginInfoByUsername.getId());
//        List<SimpleGrantedAuthority> simpleGrantedAuthorities=new ArrayList<>();
//        //遍历集合,把permissions转换为simpleGrantedAuthorities
//        for (String p:permissions){
//            SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(p);
//            simpleGrantedAuthorities.add(simpleGrantedAuthority);
//        }
        //2.
        List<SimpleGrantedAuthority> simpleGrantedAuthorities=permissions.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList());
        MySecurityUser mySecurityUser = new MySecurityUser(loginInfoByUsername);
        mySecurityUser.setAuthorities(simpleGrantedAuthorities);

        log.debug("用户名匹配成功！准备返回此用户名匹配的UserDetails类型的对象");

//        UserDetails userDetails = User.builder()
//                .username(s)
//                .password(loginInfoByUsername.getPassword())
//                .disabled(loginInfoByUsername.getEnable()==0?true:false) // 账号状态是否禁用
//                .accountLocked(false) // 账号状态是否锁定
//                .accountExpired(false) // 账号状态是否过期
//                .credentialsExpired(false) // 账号的凭证是否过期
//                .authorities("这是一个临时使用的山寨的权限！！！") // 权限
//                .build();
        log.debug("即将向Spring Security返回UserDetails类型的对象：{}", mySecurityUser);
        return mySecurityUser;
    }
}
